package nl.grol.yakshop.dataImport;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.logging.Logger;

import nl.grol.yakshop.domain.model.Gender;
import nl.grol.yakshop.domain.model.YakFactory;
import nl.grol.yakshop.domain.model.YakHerd;
import nl.grol.yakshop.domain.model.YakI;
import nl.grol.yakshop.util.YakShopException;

import org.joda.time.DateTime;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import com.google.common.collect.Lists;

public class XmlHerdImporter implements HerdImporterI {
    private static final Logger log = Logger.getLogger(XmlHerdImporter.class.getName());

	@Override
	public YakHerd loadFromResource( URL resource ) throws YakShopException {
		YakHerd herd = null;

		Serializer serializer = new Persister();
		File source = new File(resource.getFile() );

		try {
			
			LabYakHerd externalHerd = serializer.read(nl.grol.yakshop.dataImport.LabYakHerd.class, source);
			herd = convertFromExternal( externalHerd );
		
			log.info("Successfully read xml-herd from resource with yaks:" + herd.getYaks().size() );

		} catch (Exception exc) {
			throw new YakShopException("Error laoding xml-resource:" + source.getName() +
					":" + exc.getMessage() );
		}
		
		return herd;
	}
	
	@Override
	public YakHerd loadFromInputStream( InputStream is ) throws YakShopException {
		YakHerd herd = null;
		
		Serializer serializer = new Persister();

		try {
			
			LabYakHerd externalHerd = serializer.read(nl.grol.yakshop.dataImport.LabYakHerd.class, is );
			herd = convertFromExternal( externalHerd );
		
			log.info("Successfully read xml-herd from stdin with yaks:" + herd.getYaks().size() );
			
		} catch (Exception exc) {
			throw new YakShopException("Error laoding xml-resource:" + 
					":" + exc.getMessage() );
		}
		
		return herd;
	}
	
	private YakHerd convertFromExternal( LabYakHerd externalHerd  ) throws YakShopException {
		List<YakI> yaks = Lists.newArrayList();
		for( nl.grol.yakshop.dataImport.LabYak yak : externalHerd.getLabYaks()) {
			if( yak.isValid() == false ) {
				throw new YakShopException("Invalid yak with name " + yak.getName() );
			}
			/*
			 * TODO verify if name is already in use
			 */
			yaks.add( YakFactory.createYak(yak.getName(), yak.getAge(), convertSexToGender(yak.getSex())));
		}
		
		return  new YakHerd( "Example", DateTime.now(), yaks );
	}

	private Gender convertSexToGender( YakSex sex ) {
		Gender gender = Gender.unknown;
		if( sex == YakSex.f) {
			gender = Gender.female;
		} else if( sex == YakSex.m) {
			gender = Gender.male;
		}
		return gender;
	}

	
}
